package com.dave.admin.config.auth.component;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.dave.admin.config.auth.pojo.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义登录拦截器
 *
 * @author Dave
 */
@Slf4j
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private final boolean postOnly = true;

    private String METHOD_POST = "POST";

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (this.postOnly && request.getMethod().equals(METHOD_POST) && StrUtil.containsAny(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {

            UsernamePasswordAuthenticationToken authRequest = null;
            String inputLoginString = "";
            try {
                inputLoginString = IoUtil.read(request.getInputStream(), "UTF-8");
                LoginParam loginParam = JSONUtil.toBean(inputLoginString, LoginParam.class);
                authRequest = new UsernamePasswordAuthenticationToken(loginParam.getUsername().trim(), loginParam.getPassword().trim());
            } catch (Exception e) {
                authRequest = new UsernamePasswordAuthenticationToken("", "");
                log.error("自定义JSON登入报错入参 : {}", inputLoginString);
                log.error("自定义JSON登入报错:{}", e.getMessage(), e);

            }
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        } else {
            return super.attemptAuthentication(request, response);
        }
    }
}